import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:ymApp/common/http_service.dart';
import 'package:ymApp/model/banner_model.dart';
import 'package:ymApp/model/video_model.dart';
import 'package:ymApp/pages/index/grid_item.dart';
import 'package:ymApp/router/routes.dart';
import '../../extension/int_extendion.dart';

import 'package:dio/dio.dart';

/**
 *  首页
 **/

class IndexPage extends StatefulWidget {
  static String routeName = 'index';

  @override
  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> {
  List _bannerList;
  Future _videoDataFuture;
  Future _bannerListFuture;
  int count = 0;
  List<BannerModel> list;

  TabController _controller;
  List tabList = ['直播', '推荐', '追番', '热门', '影视'];
  String loadMoreText = "没有更多数据";
  TextStyle loadMoreTextStyle =
      new TextStyle(color: const Color(0xFF999999), fontSize: 14.0);
  TextStyle titleStyle =
      new TextStyle(color: const Color(0xFF757575), fontSize: 14.0);

  //初始化滚动监听器，加载更多使用
  ScrollController _loadmoreController = new ScrollController();
  int _gridLength = 5;

  Future _getBannerData() async {
    Response response =
        await HttpRequest.request('/banner/list', method: 'post');

    dynamic list = response.data['data'];

    print(list.toString());
    return list;
  }

  Future _getVideoData() async {
    Response res = await HttpRequest.request('/video/list', method: 'post');
    return res.data;
  }

  @override
  void initState() {
    print('开始首页构建');
    // TODO: implement initState
    super.initState();
    _videoDataFuture = _getVideoData();
    _bannerListFuture = _getBannerData();
//    this._getBannerData();
    _controller =
        TabController(length: tabList.length, vsync: ScrollableState());

    //固定写法，初始化滚动监听器，加载更多使用
    _loadmoreController.addListener(() {
      var maxScroll = _loadmoreController.position.maxScrollExtent;
      var pixel = _loadmoreController.position.pixels;
      if (maxScroll == pixel) {
        setState(() {
          loadMoreText = "正在加载中...";
          loadMoreTextStyle =
              new TextStyle(color: const Color(0xFF4483f6), fontSize: 14.0);
        });
      } else {
        setState(() {
          loadMoreText = "没有更多数据";
          loadMoreTextStyle =
              new TextStyle(color: const Color(0xFF999999), fontSize: 14.0);
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    print('首页构建中');
    return Scaffold(
      body: NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return <Widget>[
            SliverAppBar(
              expandedHeight: 0.rpx,
              pinned: false,
              floating: true,
              snap: true,
              backgroundColor: Colors.white,
              elevation: 0,
              shadowColor: Colors.transparent,
              forceElevated: false,
              primary: true,
              bottom: PreferredSize(
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 20.rpx),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      CircleAvatar(
                        child: Text('孟'),
                      ),
//                    SizedBox(width: 30.rpx,),
                      GestureDetector(
                        onTap: () {
                          Routes.navigateTo(context, Routes.search);
                        },
                        child: Container(
                          width: 400.rpx,
                          height: 50.rpx,
                          padding: EdgeInsets.only(left: 20.rpx),
                          alignment: Alignment.centerLeft,
                          decoration: BoxDecoration(
                              color: Colors.black12,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(100))),
                          child: Icon(
                            Icons.search,
                            color: Colors.black45,
                          ),
                        ),
                      ),
                      SizedBox(
                        width: 30.rpx,
                      ),
                      Icon(
                        Icons.videogame_asset,
                        size: 40.rpx,
                      ),
                      Icon(
                        Icons.mail,
                        size: 40.rpx,
                      )
                    ],
                  ),
                ),
              ),
            ),
            SliverPersistentHeader(
              pinned: true,
              delegate: StickyTabBarDelegate(
                child: TabBar(
                    labelColor: Colors.pink,
                    isScrollable: true,
                    indicatorColor: Colors.pink,
                    unselectedLabelColor: Colors.black,
                    labelStyle: TextStyle(
                      fontSize: 16.px,
                      fontWeight: FontWeight.w500,
                    ),
                    indicatorWeight: 5,
                    //                  indicatorPadding：EdgeInsets.all(10),
                    controller: _controller,
                    indicator: UnderlineTabIndicator(
                        insets: EdgeInsets.only(left: 30, right: 30),
                        borderSide: BorderSide(width: 4.0, color: Colors.red)),
                    tabs: this.tabList.map<Widget>((item) {
                      return tabBarItem(item);
                    }).toList()),
              ),
            ),
          ];
        },
        body: TabBarView(
          controller: _controller,
          children: [
            RefreshIndicator(
              onRefresh: () {
                return _handlerRefresh();
              },
              child: tabContent2(),
            ),
            tabContent2(),
            tabContent2(),
            tabContent2(),
            tabContent2(),
          ],
        ),
      ),
      floatingActionButton: RaisedButton(
        child: Icon(Icons.add),
        onPressed: () {
          setState(() {
            count++;
          });
        },
      ),
    );
  }

  Widget tabBarItem(String title) {
    return Container(
      width: 120.rpx,
      child: Tab(text: '$title'),
    );
  }

  Widget tabContent2() {
    return FutureBuilder(
      future: _videoDataFuture,
      builder: (ctx, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting)
          return Text('加载中');
        List<VideoModel> list = [];
        for (var item in snapshot.data['data']['list']) {
          list.add(VideoModel.fromJson(item));
        }
        return CustomScrollView(
          slivers: [
            SliverToBoxAdapter(
              child: ClipRRect(
                borderRadius: BorderRadius.all(Radius.circular(10)),
                child: Container(
                  width: MediaQuery.of(context).size.width,
                  height: 300.rpx,
                  margin: EdgeInsets.all(20.rpx),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(10.rpx))),
                  child: swiperBuilder(),
                ),
              ),
            ),
            SliverPadding(
              padding: EdgeInsets.all(20),
              sliver: SliverGrid(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                    childAspectRatio: 200 / 210,
                    mainAxisSpacing: 15,
                    crossAxisSpacing: 10),
                delegate: SliverChildBuilderDelegate((context, index) {
                  return GridItem(list[index]);
                }, childCount: list.length),
              ),
            )
          ],
        );
      },
    );
  }

  Widget tabContent() {
    return RefreshIndicator(
      onRefresh: _handlerRefresh,
      child: GridView.builder(
          controller: _loadmoreController,
          padding: EdgeInsets.symmetric(vertical: 20),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              childAspectRatio: 200 / 210,
              mainAxisSpacing: 15,
              crossAxisSpacing: 10),
          itemCount: _gridLength + 1,
          physics: const AlwaysScrollableScrollPhysics(),
          itemBuilder: (context, index) {
            if (index == _gridLength) {
              return _buildProgressMoreIndicator();
            } else {
//              return GridItem();
            }
          }),
    );
  }

  Future _handlerRefresh() async {
    await Future.delayed(Duration(seconds: 3));
    var res = _getBannerData();
    setState(() {
      _bannerListFuture = res;
      _gridLength += 5;
    });
    return;
  }

//  Future<Null> _handlerRefresh() async {
//    //模拟耗时5秒
//    await new Future.delayed(new Duration(seconds: 5));
//    setState(() {
//      _gridLength += 5;
//    });
//    return null;
//  }

  void _showSnackBar() {
    Scaffold.of(context).showSnackBar(SnackBar(
      content: Text('当前值已修改'),
      backgroundColor: Colors.black45,
      action: SnackBarAction(
        label: '撤销',
        onPressed: () => print('点击撤销了'),
      ),
      duration: Duration(milliseconds: 2000),
    ));
  }

  /**
   * 加载更多进度条
   */

  Widget _buildProgressMoreIndicator() {
    return new Padding(
      padding: const EdgeInsets.all(15.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.network(
            'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2085178611,3470768407&fm=26&gp=0.jpg',
            width: 60.rpx,
            height: 60.rpx,
          ),
          Center(
            child: Text(loadMoreText, style: loadMoreTextStyle),
          )
        ],
      ),
    );
  }

  // banner
  Widget swiperBuilder() {
    return FutureBuilder(
      future: _bannerListFuture,
      builder: (ctx, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Text('加载中');
        }
        if (snapshot.hasError) {
          return Text('请求错误');
        }
        print(snapshot.toString());
        List<BannerModel> list = [];

        for (var item in snapshot.data) {
          list.add(BannerModel.fromJson(item));
        }
        return Swiper(
          scrollDirection: Axis.horizontal,
          itemCount: list.length,
          autoplay: true,
          itemBuilder: (BuildContext context, int index) {
            return ClipRRect(
              borderRadius: BorderRadius.all(Radius.circular(10)),
              child: Image.network(
                list[index].url,
                fit: BoxFit.cover,
              ),
            );
          },
          pagination: SwiperPagination(
              alignment: Alignment.bottomCenter,
              builder: DotSwiperPaginationBuilder(
                activeColor: Colors.red,
                color: Colors.white,
              )),
          viewportFraction: 0.8,
          scale: 0.8,
          layout: SwiperLayout.DEFAULT,
          itemWidth: MediaQuery.of(context).size.width,
          itemHeight: MediaQuery.of(context).size.height,
        );
      },
    );
  }
}

class MySliverPersistentHeaderDelegate extends SliverPersistentHeaderDelegate {
  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
        color: Colors.blue,
        alignment: Alignment.center,
        child: Text('我是一个SliverPersistentHeader',
            style: TextStyle(color: Colors.white)));
  }

  @override
  double get maxExtent => 200.0;

  @override
  double get minExtent => 26.rpx;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) =>
      false; // 如果内容需要更新，设置为true
}

class StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
  final TabBar child;

  StickyTabBarDelegate({@required this.child});

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    print(overlapsContent);
    return Container(
      color: Colors.white,
      child: Column(
        children: [this.child],
      ),
    );
  }

  @override
  double get maxExtent => this.child.preferredSize.height;

  @override
  double get minExtent => this.child.preferredSize.height;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}
